//
//  TRFindViewTableViewCell.m
//  WeiMiLan
//
//  Created by anan on 14/11/15.
//  Copyright (c) 2014年 Mac. All rights reserved.
//

#import "TRFindViewTableViewCell.h"

@implementation TRFindViewTableViewCell

- (void)awakeFromNib {
    //  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(homeCommetnCountChanged:) name:@"kHomeCommetnCountChanged" object:nil];
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    [[NSUserDefaults standardUserDefaults]setObject:self.info forKey:@"DetailInfo"];
    // Configure the view for the selected state
}

//按比例缩放,size 是你要把图显示到 多大区域 CGSizeMake(300, 140)

-(UIImage *) imageCompressForSize:(UIImage *)sourceImage targetSize:(CGSize)size{
    
    UIImage *newImage = nil;
    
    CGSize imageSize = sourceImage.size;
    
    CGFloat width = imageSize.width;
    
    CGFloat height = imageSize.height;
    
    CGFloat targetWidth = size.width;
    
    CGFloat targetHeight = size.height;
    
    CGFloat scaleFactor = 0.0;
    
    CGFloat scaledWidth = targetWidth;
    
    CGFloat scaledHeight = targetHeight;
    
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        CGFloat widthFactor = targetWidth / width;
        
        CGFloat heightFactor = targetHeight / height;
        
        if(widthFactor > heightFactor){
            
            scaleFactor = widthFactor;
            
        }
        
        else{
            
            scaleFactor = heightFactor;
            
        }
        
        scaledWidth = width * scaleFactor;
        
        scaledHeight = height * scaleFactor;
        
        if(widthFactor > heightFactor){
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            
        }else if(widthFactor < heightFactor){
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            
        }
        
    }
    
    UIGraphicsBeginImageContext(size);
    
    CGRect thumbnailRect = CGRectZero;
    
    thumbnailRect.origin = thumbnailPoint;
    
    thumbnailRect.size.width = scaledWidth;
    
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        
        NSLog(@"scale image fail");
        
    }
    
    UIGraphicsEndImageContext();
    
    return newImage;
    
}
-(UIImage *)doWithPic:(UIImage *)image{
//    CGSize size=CGSizeMake(image.size.width, image.size.height/3);
//    image=[self imageCompressForSize:image targetSize:size];
    //*************** 截取小图 ******************
    CGRect rect1 = CGRectMake(0, 0, 400, 250);//创建矩形框
    //对图片进行截取
    UIImage * image2 = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([image CGImage], rect1)];
    return image2;
}

- (void)setInfo:(NSDictionary *)info
{

    if (self.weixinView==nil) {
        NSArray *weixinBtn = [[NSBundle mainBundle]loadNibNamed:@"TRWeixin" owner:self options:nil];
        self.weixinView = [weixinBtn lastObject];
    }
    _info = info;
    
    // NSLog(@"%@",info);
    
    //  [self updateLabel];
    
    //  [self setNeedsDisplay];
    
    self.imageViewCover.contentMode=UIViewContentModeScaleToFill;
    
    self.labelFollowCount.text = [NSString stringWithFormat:@"%d",[info ql_intForKey:@"F_HIGHLIGHT"]];
    self.labelCommentCount.text = [NSString stringWithFormat:@"%d",[info ql_intForKey:@"COMMENT_NUM"]];
    self.labelUserName.text = info[@"USER_NAME"];
   // NSLog(@"名字：%@",self.labelUserName.text);
    
    if ([info ql_hasObjectForKey:@"THUMBNAIL_URL"]) {
        NSString *imgUrl = [info ql_stringForKey:@"THUMBNAIL_URL"];
        imgUrl = [imgUrl stringByReplacingOccurrencesOfString:@"_smaller" withString:@""];
        UIImageView *imgView=[[UIImageView alloc]init];
        [imgView sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"nodata_publics"]];
        float ww=imgView.image.size.width;
        float hh=imgView.image.size.height;
        if (hh>1200.0) {
            imgView.image=[self doWithPic:imgView.image];
        }
        UIImage *img=imgView.image;
//        [self.imageViewCover setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"nodata_publics"]];
        self.imageViewCover.image=img;

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSDate *createDate = [formatter dateFromString:[self.info ql_stringForKey:@"CREATE_DATE"]];
        
        
        NSString *str = [NSString stringWithFormat:@"%@",[createDate ql_ToString]];
        str = [str substringFromIndex:5];
        self.timeLabel.text =str;

        self.labelDesc.text = [info ql_stringForKey:@"DESCRIPTION"];

    }else{
        [self.imageViewCover setImage:nil];
    }
    
    self.imageViewUserHeader.layer.masksToBounds = YES;
    self.imageViewUserHeader.layer.cornerRadius = 16; //设置图片圆角的尺度
    [self.imageViewUserHeader sd_setImageWithURL:[NSURL URLWithString:[info ql_stringForKey:@"HEAD_PIC_URL"]] placeholderImage:[UIImage imageNamed:@"nodata_avator"]];
    
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    int followId = [self.info ql_intForKey:@"USER_ID"];
    if (followId==0) {
        NSDictionary *dic = self.info[@"USER_INFO"];
        followId = [dic ql_intForKey:@"ID"];
        [self.imageViewUserHeader sd_setImageWithURL:[NSURL URLWithString:[dic ql_stringForKey:@"HEAD_PIC_URL"]] placeholderImage:[UIImage imageNamed:@"icon"]];
        self.labelUserName.text = [dic ql_stringForKey:@"NAME"];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSDate *createDate = [formatter dateFromString:[self.info ql_stringForKey:@"CREATE_DATE"]];
        

        self.timeLabel.text =[NSString stringWithFormat:@"%@",[[self.info ql_stringForKey:@"CREATE_DATE"] substringFromIndex:5]];
        
    }
    if ([[QLFollowManager shareInstance] isFollowWithUserId:followId myUserId:[userInfo  ql_intForKey:@"ID"]]) {
        [self.buttonFollow setTitle:@"已关注" forState:UIControlStateNormal];
    }else{
        [self.buttonFollow setTitle:@"关注" forState:UIControlStateNormal];
    }
    
    if ([info ql_hasObjectForKey:@"TONE_URL"]) {
        self.viewPlay.hidden = NO;
        if ([info ql_hasObjectForKey:@"TONE_TIME"]) {
            if ([[info ql_stringForKey:@"TONE_TIME"] isEqualToString:@"null"]) {
                self.labelTLong.text = [NSString stringWithFormat:@"%@'",@""];
            } else {
                self.labelTLong.text = [NSString stringWithFormat:@"%@'",[info ql_stringForKey:@"TONE_TIME"]];
            }
            
            
            self.labelUserName.text = [info ql_stringForKey:@"NAME"];
        }
    }else{
        self.viewPlay.hidden = YES;
    }
    
    [self updateFavButton];
    
    //    if ([QLPublic isAdminAccount]) {
    //        self.buttonDownLine.hidden = NO;
    //    }else{
    //        self.buttonDownLine.hidden = YES;
    //    }
}


- (float)getHeight
{
    int h = self.frame.size.height;
    return h;
}

- (IBAction)buttonFollowAction:(id)sender
{
    int followId = [self.info ql_intForKey:@"USER_ID"];
    if (followId==0) {
        NSDictionary *dic = self.info[@"USER_INFO"];
        followId = [dic ql_intForKey:@"ID"];
    }
    
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    BOOL b = [[QLFollowManager shareInstance] isFollowWithUserId:followId myUserId:[userInfo ql_intForKey:@"ID"]];
    if (b) {
        [[QLFollowManager shareInstance] deleteFollowWithUserId:followId myUserId:[userInfo ql_intForKey:@"ID"] callback:^(BOOL isCache, id data) {
            self.info = _info;
            [[NSNotificationCenter defaultCenter]postNotificationName:@"kRefreshFollow" object:nil];
        }];
    }else{
        [[QLFollowManager shareInstance] addFollowWithUserId:followId myUserId:[userInfo ql_intForKey:@"ID"] callback:^(BOOL isCache, id data) {
            self.info = _info;
            [[NSNotificationCenter defaultCenter]postNotificationName:@"kRefreshFollow" object:nil];
        }];
    }

}

- (IBAction)buttonShareAction:(id)sender
{
    ApplicationDelegate.shareContent=self.info[@"DESCRIPTION"];
    ApplicationDelegate.shareTitle=self.info[@"NAME"];
    ApplicationDelegate.shareURL=self.info[@"SHARE_URL"];
    ApplicationDelegate.shareImage = self.imageViewCover.image;
    
    // bei 分享 首页
    
    NSArray*shareButtonTitleArray = @[@"微信",@"微信朋友圈",@"QQ",@"新浪微博",@"QQ空间",@"复制"];
    NSArray * shareButtonImageNameArray= @[@"sns_icon_22",@"sns_icon_23",@"sns_icon_40",@"sns_icon_1",@"QQkj",@"fuzhi"];
    
    self.lxActivity = [[LXActivity alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" ShareButtonTitles:shareButtonTitleArray withShareButtonImagesName:shareButtonImageNameArray];
    [self.lxActivity showInView:ApplicationDelegate.window];
    [ApplicationDelegate.window insertSubview:self.lxActivity aboveSubview:self.weixinView];
}

#pragma mark ----分享视图代理
- (void)didClickOnImageIndex:(NSInteger )imageIndex
{
    switch (imageIndex) {
        case 0:
            [ApplicationDelegate changeScene:0];
            [ApplicationDelegate sendLinkContent];
            break;
        case 1:
            [ApplicationDelegate changeScene:1];
            [ApplicationDelegate sendLinkContent];
            break;
        case 2: //QQ分享
            
            [UMSocialQQHandler setQQWithAppId:QQWithAppId appKey:QQWithAppKey url:ApplicationDelegate.shareURL];
            
            [self yixunshare:UMShareToQQ];
            
            break;
        case 3: //新浪微博
            
            
            [self yixunshare:UMShareToSina];
            break;
        case 4://QQ空间
            
            [UMSocialQQHandler setQQWithAppId:QQWithAppId appKey:QQWithAppKey url:ApplicationDelegate.shareURL];
            
            
            [self yixunshare:UMShareToQzone];
            break;
        case 5:
        {
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string =[NSString stringWithFormat:@"%@\n%@",ApplicationDelegate.shareContent,ApplicationDelegate.shareURL];
            [SVProgressHUD showErrorWithStatus:@"网址已经复制，您可以直接发送给好友"];
        }break;
            //        case 6:
            //            //设置易信Appkey和分享url地址
            //            [UMSocialYixinHandler setYixinAppKey:YiXunWithAppId url:ApplicationDelegate.shareURL];
            //            [self yixunshare:UMShareToYXSession];
            //            break;
            //        case 7:
            //            //设置易信Appkey和分享url地址
            //            [UMSocialYixinHandler setYixinAppKey:YiXunWithAppId url:ApplicationDelegate.shareURL];
            //            [self yixunshare:UMShareToYXTimeline];
            //            break;
            
        default:
            break;
    }
}

-(void)yixunshare:(NSString *)pingtai
{
    NSString *shareText = ApplicationDelegate.shareContent;
    UIImage *shareImage = ApplicationDelegate.shareImage;
    
    if ([pingtai isEqualToString:UMShareToSina]) {
        shareText = [NSString stringWithFormat:@"%@%@",ApplicationDelegate.shareContent,ApplicationDelegate.shareURL];
        shareImage=ApplicationDelegate.shareImageHD;
    }
    UMSocialUrlResource *UMUrl=[[UMSocialUrlResource alloc] initWithSnsResourceType:UMSocialUrlResourceTypeDefault url:ApplicationDelegate.shareURL];
    
    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[pingtai] content:shareText image:shareImage location:nil urlResource:UMUrl presentedController:self.viewController completion:^(UMSocialResponseEntity * response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"成功" message:@"分享成功" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
            [alertView show];
        } else if(response.responseCode != UMSResponseCodeCancel) {
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"失败" message:@"分享失败" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
            [alertView show];
        }
    }];
}

- (IBAction)buttonCommentAction:(id)sender
{
    
    TRProductDetailViewController *vc = [[TRProductDetailViewController alloc] init];
    vc.productTypeId = self.info[@"ID"];
    [self.viewController presentViewController:vc animated:YES completion:^{
        [vc.textFieldContent becomeFirstResponder];
      
    }];

}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    // UITextField *tf = [alertView textFieldAtIndex:0];
}
- (void)updateFavButton
{
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    int uid = [userInfo ql_intForKey:@"ID"];
    int productId = [self.info ql_intForKey:@"ID"];
    
    BOOL b = [[QLFavoriteManager shareInstance] isFavoriteWithUserId:uid productId:productId];
    if (b) {
        [self.imageViewFav setImage:[UIImage imageNamed:@"iconfont-shoucang-(s)"]];
    }else{
        [self.imageViewFav setImage:[UIImage imageNamed:@"iconfont-shoucang-(3)"]];
    }
}

- (IBAction)buttonFavAction:(id)sender
{
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    int uid = [userInfo ql_intForKey:@"ID"];
    int productId = [self.info ql_intForKey:@"ID"];
    
    BOOL b = [[QLFavoriteManager shareInstance] isFavoriteWithUserId:uid productId:productId];
    if (b) {
        [[QLFavoriteManager shareInstance] deleteFavoriteWithUserId:uid productId:productId callback:^(BOOL isCache, id data) {
            [self updateFavButton];
            if (data) {
                int favCount = (int)[self.labelFollowCount.text integerValue];
                if (favCount > 0) {
                    self.labelFollowCount.text = [NSString stringWithFormat:@"%d",(favCount-1)];
                }
                
                //  self.labelFollowCount.text = [NSString stringWithFormat:@"%d",100];
            }
        }];
    }else{
        [[QLFavoriteManager shareInstance] addFavoriteWithUserId:uid productId:productId callback:^(BOOL isCache, id data) {
            [self updateFavButton];
            if (data) {
                int favCount = (int)[self.labelFollowCount.text integerValue];
                self.labelFollowCount.text = [NSString stringWithFormat:@"%d",(favCount+1)];
                //  self.labelFollowCount.text = [NSString stringWithFormat:@"%d",100];
            }
        }];
    }
}

- (IBAction)buttonUserDetailAction:(id)sender
{
    int uid = [self.info ql_intForKey:@"USER_ID"];
    if (uid<=0) {
        NSDictionary *dic = self.info[@"USER_INFO"];
        uid = [dic ql_intForKey:@"ID"];
    }
    [QLPlayerManager openUserHomeWithId:uid viewController:self.viewController];
}

- (IBAction)buttonPlayAction:(id)sender
{
    NSString *url = [self.info ql_stringForKey:@"TONE_URL"];
    [[QLRecordPlayer shareInstance] play:[NSURL URLWithString:url]];
}

- (IBAction)buttonDownLineAction:(id)sender
{
    NSDictionary *ui = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic ql_setObject:[ui ql_stringForKey:@"ID"] forKey:@"userId"];
    [dic ql_setObject:[self.info ql_stringForKey:@"ID"] forKey:@"ID"];
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [requestManager GET:@"http://ping.vsmu.cn/app/Interface/Product?type=2009" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [SVProgressHUD showSuccessWithStatus:responseObject[@"MESSAGE_INFO"][@"MESSAGE"]];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:STR_MSG_NETWORK_ERROR];
    }];
}
-(void)updateLabel {
    NSDate* now = [NSDate date];
    NSCalendar *cal = [NSCalendar currentCalendar];
    
    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit;
    NSDateComponents *dd = [cal components:unitFlags fromDate:now];
    // NSInteger y = [dd year];
    NSInteger m = [dd month];
    NSInteger d = [dd day];
    
    NSInteger hour = [dd hour];
    NSInteger min = [dd minute];
    //  NSInteger sec = [dd second];
    
    self.timeLabel.text = [NSString stringWithFormat:@"%02ld-%02ld-%02ld:%02ld",(long)m,(long)d,(long)hour,(long)min];
    
}
@end
